/*
 Copyright (c) 2013 Katsuma Tanaka
 
 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#import "QBAssetCollectionViewController.h"
#import <QuartzCore/QuartzCore.h>
// Views
#import "QBImagePickerAssetCell.h"
#import "QBImagePickerFooterView.h"

#import "UIButtonFactory.h"
#import "UIUtil.h"
#import "MicroDef.h"
#import "CHImageScanView.h"
#import "QBImagePickerAssetView.h"
#import "ISTThemeButton.h"
#import "ChildHoodService.h"



#define ToolViewBtnHSpace   (HARDWARE_SCREEN_WIDTH-2*ToolViewBtnWidth)/3.
#define ToolViewBtnVSpace   2
#define ToolViewBtnWidth    144.5

#define PreviewText  @"预览"
#define SendMessageText  @"发送"


@interface QBAssetCollectionViewController ()
{
    UIImageView *_imgView;
}

@property (nonatomic, strong) NSMutableArray *assets;
@property (nonatomic, strong) NSMutableOrderedSet *selectedAssets;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *doneButton;
@property (nonatomic, strong) UIButton *previewButton;


- (void)reloadData;
- (void)updateRightBarButtonItem;
- (void)updateDoneButton;
- (void)done;
- (void)cancel;

@end

@implementation QBAssetCollectionViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        
//        [CNMultiThemeManager registerForThemeChange:self];

        /* Initialization */
        self.assets = [NSMutableArray array];
        self.selectedAssets = [NSMutableOrderedSet orderedSet];
        
        self.imageSize = CGSizeMake(75, 75);

        [self.view addSubview:[self toolView]];
        
        // Table View
        UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.allowsSelection = YES;
        tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        
        [self.view addSubview:tableView];
        self.tableView = tableView;
        self.view.backgroundColor = RGBCOLOR(247, 243, 229);
        self.tableView.backgroundColor = RGBCOLOR(247, 243, 229);
        self.tableView.separatorColor = RGBCOLOR(247, 243, 229);
        
        
    }
    
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    UIView* vi = [UIUtil getAViewWithSize:CGSizeMake(HARDWARE_SCREEN_WIDTH, 30) backGroundColor:CommonColor];
    [vi setCenter:CGPointMake(HARDWARE_SCREEN_WIDTH/2, -15)];
    [self.view addSubview:vi];
    [self.navigationItem setHidesBackButton:YES];
    
    
    CGRect ff =self.tableView.frame;
    CGRect ff1 = self.view.frame;

    ff.size.height = ff1.size.height - 44;
    self.tableView.frame = ff;
    
    // Reload
    [self reloadData];
    
    if (self.fullScreenLayoutEnabled) {
        // Set bar styles
        self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
        self.navigationController.navigationBar.translucent = YES;
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackTranslucent animated:NO];
        
        CGFloat top = 0;
        if (![[UIApplication sharedApplication] isStatusBarHidden]) top = top+20;
        if (!self.navigationController.navigationBarHidden) top = top+44;
        self.tableView.contentInset = UIEdgeInsetsMake(top, 0, 0, 0);
        self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(top, 0, 0, 0);
        
        [self setWantsFullScreenLayout:YES];
    }
    
    // Scroll to bottom
 //   NSInteger numberOfRows = [self.tableView numberOfRowsInSection:2];
  //  NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(numberOfRows - 1) inSection:2];
  //  [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    
    // Flash scroll indicators
    [self.tableView flashScrollIndicators];
}


-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)setShowsCancelButton:(BOOL)showsCancelButton
{
    _showsCancelButton = showsCancelButton;
    
    [self updateRightBarButtonItem];
}

- (void)setAllowsMultipleSelection:(BOOL)allowsMultipleSelection
{
    _allowsMultipleSelection = allowsMultipleSelection;
    
    [self updateRightBarButtonItem];
}


#pragma mark - Instance Methods

- (void)reloadData
{
    // Reload assets
    
    //[result valueForProperty:ALAssetPropertyDate]
    
    [self.assetsGroup enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
        if (result) {
            [self.assets insertObject:result atIndex:0];
//            NSDate* date = [result valueForProperty:ALAssetPropertyDate];
//            NSLog(@"sssss::%@", date);
        }
    }];
    
   // self.assets sortUsingSelector:
    [self.tableView reloadData];
    
    // Set footer view
    if (self.showsFooterDescription) {
        [self.assetsGroup setAssetsFilter:[ALAssetsFilter allPhotos]];
        NSUInteger numberOfPhotos = self.assetsGroup.numberOfAssets;
        
        [self.assetsGroup setAssetsFilter:[ALAssetsFilter allVideos]];
        NSUInteger numberOfVideos = self.assetsGroup.numberOfAssets;
        
        switch(self.filterType) {
            case QBImagePickerFilterTypeAllAssets:
                [self.assetsGroup setAssetsFilter:[ALAssetsFilter allAssets]];
                break;
            case QBImagePickerFilterTypeAllPhotos:
                [self.assetsGroup setAssetsFilter:[ALAssetsFilter allPhotos]];
                break;
            case QBImagePickerFilterTypeAllVideos:
                [self.assetsGroup setAssetsFilter:[ALAssetsFilter allVideos]];
                break;
        }
        
        QBImagePickerFooterView *footerView = [[QBImagePickerFooterView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 48)];
        
        if (self.filterType == QBImagePickerFilterTypeAllAssets) {
            footerView.titleLabel.text = [self.delegate assetCollectionViewController:self descriptionForNumberOfPhotos:numberOfPhotos numberOfVideos:numberOfVideos];
        } else if (self.filterType == QBImagePickerFilterTypeAllPhotos) {
            footerView.titleLabel.text = [self.delegate assetCollectionViewController:self descriptionForNumberOfPhotos:numberOfPhotos];
        } else if (self.filterType == QBImagePickerFilterTypeAllVideos) {
            footerView.titleLabel.text = [self.delegate assetCollectionViewController:self descriptionForNumberOfVideos:numberOfVideos];
        }
        
        self.tableView.tableFooterView = footerView;
    } else {
        QBImagePickerFooterView *footerView = [[QBImagePickerFooterView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 4)];
        
        footerView.backgroundColor=[UIColor clearColor];
        self.tableView.tableFooterView = footerView;
    }
    
    if([self.view isKindOfClass:[UIScrollView class]])
    {
//        NSLog(@"dada");
    }
    //self.view
}

- (void)updateRightBarButtonItem
{
    if (self.allowsMultipleSelection) {
        // Set done button
//        UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(done)];
//        doneButton.enabled = NO;
//        
//        [self.navigationItem setRightBarButtonItem:doneButton animated:NO];
//        self.doneButton = doneButton;
    } else if (self.showsCancelButton) {
        // Set cancel button
        UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancel)];
        
        [self.navigationItem setRightBarButtonItem:cancelButton animated:NO];
    } else {
        [self.navigationItem setRightBarButtonItem:nil animated:NO];
    }
}

- (void)updateDoneButton
{
    //if (self.limitsMinimumNumberOfSelection) {
        self.doneButton.enabled = (self.selectedAssets.count > 0);
        self.previewButton.enabled = (self.selectedAssets.count > 0);
        if(self.selectedAssets.count <= 0)
        {
            [self. previewButton setTitle:self.previewText forState:UIControlStateNormal];
            
            //bug 6094 fixed by 荣则兵
            [self. doneButton setTitle:self.oprationText forState:UIControlStateNormal];

        }
        else{
            [self. previewButton setTitle:[NSString stringWithFormat:@"%@(%zd)",self.previewText, self.selectedAssets.count] forState:UIControlStateNormal];
            [self. doneButton setTitle:[NSString stringWithFormat:@"%@(%zd)",self.oprationText, self.selectedAssets.count]  forState:UIControlStateNormal];
        }
        
        
 //   }

//else {
//        self.doneButton.enabled = (self.selectedAssets.count > 0);
//    }
}

- (void)done
{
    [self.delegate assetCollectionViewController:self didFinishPickingAssets:self.selectedAssets.array];
}

- (void)cancel
{
    [self.delegate assetCollectionViewControllerDidCancel:self];
}


-(void)preview
{

    NSMutableArray* mArray = [NSMutableArray array];
    for(ALAsset* asset in self.selectedAssets)
    {
        [mArray addObject:[UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]]];
        
        
    }
    if(mArray.count <=0)return;
    
    CHImageScanView *scan = [CHImageScanView sharedInstance];
    scan.imageArray = mArray;
    scan.chMessages = nil;
    [scan showImage];
    

}


-(void)sendMessage
{
    [self done];

}



 - (UIView *)toolView
 {
/*
     [toolViewTmp setBackgroundColor:RGBCOLOR(247, 243, 229)];
 
    [UIButton buttonWithType:UIButtonTypeCustom];
     [preview setTag:1202];
     [preview setFrame:CGRectMake(0, 5, HARDWARE_SCREEN_WIDTH/2, 34.5)];
     [preview setBackgroundImage:[UIImage imageNamed:@"wide_btn_normal.png"] forState:UIControlStateNormal];
     [preview addTarget:self action:@selector(preview) forControlEvents:UIControlEventTouchUpInside];
     
     [preview setTitle:PreviewText forState:UIControlStateNormal];
     [preview.titleLabel setFont:[UIFont boldSystemFontOfSize:16]];
     [preview.titleLabel setTextColor:[UIColor whiteColor]];
     

     UIButton *send = [UIButton buttonWithType:UIButtonTypeCustom];
     [send setTag:1203];
     [send setFrame:CGRectMake(HARDWARE_SCREEN_WIDTH/2, 5, HARDWARE_SCREEN_WIDTH/2, 34.5)];
     
     [send setTitle:SendMessageText forState:UIControlStateNormal];
     [send.titleLabel setFont:[UIFont boldSystemFontOfSize:16]];
     [send.titleLabel setTextColor:[UIColor whiteColor]];

     
     
     [send setBackgroundImage:[UIImage imageNamed:@"wide_btn_normal.png"] forState:UIControlStateNormal];
     [send addTarget:self action:@selector(sendMessage) forControlEvents:UIControlEventTouchUpInside];


     [toolViewTmp addSubview:imgView];
     [toolViewTmp addSubview:preview];
     [toolViewTmp addSubview:send];
     self.previewButton = preview;
     self.doneButton = send;
 
 */
     
     
     UIView *toolViewTmp = [[UIView alloc] initWithFrame:CGRectMake(0, HARDWARE_SCREEN_HEIGHT - 108, HARDWARE_SCREEN_WIDTH, 44)];
     _imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, HARDWARE_SCREEN_WIDTH, 44)];
     [_imgView setImage:[[UIImage imageNamed:@"tabbarview_background.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(43, 50, 0, 50) resizingMode:UIImageResizingModeStretch]];
     
      ISTThemeButton *preview  = [UIButtonFactory buttonWithType:UIButtonTypeCustom
                                        title:PreviewText
                                        frame:CGRectMake(10, 5, (HARDWARE_SCREEN_WIDTH-20-2*10)/2, 34.5)
                                    imageName:@"wide_btn_normal.png"
                              tappedImageName:@"wide_btn_normal.png"
                                       target:self
                                       action:@selector(preview)
                                          tag:1202];
     
     
     self.previewButton = preview;
     
     [toolViewTmp addSubview:preview];
     
     
     [preview setTitleColor:RGBCOLORWITH16COLOR(0xfd8584) forState:UIControlStateNormal];
     
     [preview setTitleColor:[UIUtil colorWithHexString:@"#bfc0c0" withAlpha:1] forState:UIControlStateHighlighted];
     
     
     
     ISTThemeButton *send = [UIButtonFactory buttonWithType:UIButtonTypeCustom
                                         title:SendMessageText
                                         frame:CGRectMake(preview.frame.origin.x+preview.frame.size.width+20, 5, (HARDWARE_SCREEN_WIDTH-20 -2*10)/2, 34.5)
                                     imageName:@"wide_btn_normal.png"
                               tappedImageName:@"wide_btn_normal.png"
                                        target:self
                                        action:@selector(sendMessage)
                                           tag:1203];
     
     
     
     [send setTitleColor:RGBCOLORWITH16COLOR(0xfd8584) forState:UIControlStateNormal];
     
     [send setTitleColor:[UIUtil colorWithHexString:@"#bfc0c0" withAlpha:1] forState:UIControlStateHighlighted];
     
     
     [toolViewTmp addSubview:_imgView];
     [toolViewTmp addSubview:preview];
     [toolViewTmp addSubview:send];
     self.previewButton = preview;
     self.doneButton = send;

     
     
     return toolViewTmp;
}




#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger numberOfRowsInSection = 0;
    
    switch(section) {
        case 0: case 1:
        {
            if (self.allowsMultipleSelection && !self.limitsMaximumNumberOfSelection && self.showsHeaderButton) {
                numberOfRowsInSection = 1;
            }
        }
            break;
        case 2:
        {
            NSInteger numberOfAssetsInRow = self.view.bounds.size.width / self.imageSize.width;
            numberOfRowsInSection = self.assets.count / numberOfAssetsInRow;
            if ((self.assets.count - numberOfRowsInSection * numberOfAssetsInRow) > 0) numberOfRowsInSection++;
        }
            break;
    }
    
    return numberOfRowsInSection;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    
    switch(indexPath.section) {
        case 0:
        {
            NSString *cellIdentifier = @"HeaderCell";
            cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
                cell.selectionStyle = UITableViewCellSelectionStyleBlue;
            }
            
            if (self.selectedAssets.count == self.assets.count) {
                cell.textLabel.text = [self.delegate descriptionForDeselectingAllAssets:self];
                
                // Set accessory view
                UIImageView *accessoryView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 23, 23)];
                accessoryView.image = [UIImage imageNamed:@"minus.png"];
                
                accessoryView.layer.shadowColor = [[UIColor colorWithWhite:0 alpha:1.0] CGColor];
                accessoryView.layer.shadowOpacity = 0.70;
                accessoryView.layer.shadowOffset = CGSizeMake(0, 1.4);
                accessoryView.layer.shadowRadius = 2;
                
                cell.accessoryView = accessoryView;
            } else {
                cell.textLabel.text = [self.delegate descriptionForSelectingAllAssets:self];
                
                // Set accessory view
                UIImageView *accessoryView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 23, 23)];
                accessoryView.image = [UIImage imageNamed:@"plus.png"];
                
                accessoryView.layer.shadowColor = [[UIColor colorWithWhite:0 alpha:1.0] CGColor];
                accessoryView.layer.shadowOpacity = 0.70;
                accessoryView.layer.shadowOffset = CGSizeMake(0, 1.4);
                accessoryView.layer.shadowRadius = 2;
                
                cell.accessoryView = accessoryView;
            }
        }
            break;
        case 1:
        {
            NSString *cellIdentifier = @"SeparatorCell";
            cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
                // Set background view
                UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 1)];
                
                cell.backgroundColor = RGBCOLOR(247, 243, 229);
              //  backgroundView.backgroundColor = [UIColor colorWithWhite:0.878 alpha:1.0];
                
                cell.backgroundView = backgroundView;
            }
        }
            break;
        case 2:
        {
            NSString *cellIdentifier = @"AssetCell";
            cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            
            if (cell == nil) {
                NSInteger numberOfAssetsInRow = self.view.bounds.size.width / self.imageSize.width;
                CGFloat margin = round((self.view.bounds.size.width - self.imageSize.width * numberOfAssetsInRow) / (numberOfAssetsInRow + 1));
                
                cell = [[QBImagePickerAssetCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier imageSize:self.imageSize numberOfAssets:numberOfAssetsInRow margin:margin];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                [(QBImagePickerAssetCell *)cell setDelegate:self];
                [(QBImagePickerAssetCell *)cell setAllowsMultipleSelection:self.allowsMultipleSelection];
            }
            
            
            // Set assets
            NSInteger numberOfAssetsInRow = self.view.bounds.size.width / self.imageSize.width;
            NSInteger offset = numberOfAssetsInRow * indexPath.row;
            NSInteger numberOfAssetsToSet = (offset + numberOfAssetsInRow > self.assets.count) ? (self.assets.count - offset) : numberOfAssetsInRow;
            
            NSMutableArray *assets = [NSMutableArray array];
            for (NSUInteger i = 0; i < numberOfAssetsToSet; i++) {
                ALAsset *asset = [self.assets objectAtIndex:(offset + i)];
                
                [assets addObject:asset];
            }
            
            [(QBImagePickerAssetCell *)cell setAssets:assets];
            
            for (NSUInteger i = 0; i < numberOfAssetsToSet; i++) {
                ALAsset *asset = [self.assets objectAtIndex:(offset + i)];
                
                if ([self.selectedAssets containsObject:asset]) {
                    [(QBImagePickerAssetCell *)cell selectAssetAtIndex:i];
                } else {
                    [(QBImagePickerAssetCell *)cell deselectAssetAtIndex:i];
                }
            }
        }
            break;
    }
    
    cell.backgroundColor = RGBCOLOR(247, 243, 229);

    return cell;
}


#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat heightForRow = 0;
    
    switch(indexPath.section) {
        case 0:
        {
            heightForRow = 44;
        }
            break;
        case 1:
        {
            heightForRow = 1;
        }
            break;
        case 2:
        {
            NSInteger numberOfAssetsInRow = self.view.bounds.size.width / self.imageSize.width;
            CGFloat margin = round((self.view.bounds.size.width - self.imageSize.width * numberOfAssetsInRow) / (numberOfAssetsInRow + 1));
            heightForRow = margin + self.imageSize.height;
        }
            break;
    }
    
    return heightForRow;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0) {
        if (self.selectedAssets.count == self.assets.count) {
            // Deselect all assets
            [self.selectedAssets removeAllObjects];
        } else {
            // Select all assets
            if(self.selectedAssets.count>=self.maximumNumberOfSelection){
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                            message:[NSString stringWithFormat:@"最多能选择%zd张照片",self.maximumNumberOfSelection]
                                                           delegate:nil
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil];
            [alert show];
                return;
            }
            
            [self.selectedAssets addObjectsFromArray:self.assets];
        }
        
        // Set done button state
        [self updateDoneButton];
        
        // Update assets
        if (self.showsFooterDescription) {
            [tableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationNone];
        }
        
        // Update header text
        if (self.showsHeaderButton) {
            [tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
        }
        
        // Cancel table view selection
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
}


#pragma mark - QBImagePickerAssetCellDelegate

- (BOOL)assetCell:(QBImagePickerAssetCell *)assetCell canSelectAssetAtIndex:(NSUInteger)index
{
    BOOL canSelect = YES;
    
    if (self.allowsMultipleSelection && self.limitsMaximumNumberOfSelection) {
        canSelect = (self.selectedAssets.count < self.maximumNumberOfSelection);
    }
    
    return canSelect;
}

- (void)assetCell:(QBImagePickerAssetCell *)assetCell didChangeAssetSelectionState:(BOOL)selected atIndex:(NSUInteger)index
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:assetCell];
 
    NSInteger numberOfAssetsInRow = self.view.bounds.size.width / self.imageSize.width;
    NSInteger assetIndex = indexPath.row * numberOfAssetsInRow + index;
    ALAsset *asset = [self.assets objectAtIndex:assetIndex];
    
    if (self.allowsMultipleSelection) {
        if (selected) {
            
            if(self.selectedAssets.count>=self.maximumNumberOfSelection){
                
                QBImagePickerAssetView * view = (QBImagePickerAssetView*)[assetCell viewWithTag:index+1];
                
                view.selected =  NO;
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                                message:[NSString stringWithFormat:@"最多能选择%zd张照片",self.maximumNumberOfSelection]
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
                return;
            }else{

                [self.selectedAssets addObject:asset];
            }
        } else {
            [self.selectedAssets removeObject:asset];
        }
        
        // Set done button state
        [self updateDoneButton];
        
        // Update header text
        if (self.showsHeaderButton) {
            if ((selected && self.selectedAssets.count == self.assets.count) ||
               (!selected && self.selectedAssets.count == self.assets.count - 1)) {
                [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
            }
        }
    } else {
        [self.delegate assetCollectionViewController:self didFinishPickingAsset:asset];
    }
}

#pragma mark - 换肤
-(void)applyTheme{
    if (_imgView) {
        [_imgView setImage:[[UIImage imageNamed:@"tabbarview_background.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(43, 50, 0, 50) resizingMode:UIImageResizingModeStretch]];
    }
}

@end
